package com.heima.admin.gateway.filter;

import com.heima.admin.gateway.util.AppJwtUtil;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;

import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.function.Consumer;

/**
 * @Author ZhangXiXi
 * @Description TODO
 * @date 2021/2/20 10:14
 * @Version 1.0
 */
@Component
@Slf4j
public class AuthorizeFilter implements GlobalFilter, Ordered {
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        //1 获取request和response对象
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();

        //2 是否是登录请求 如果是登录 需要放行
        if (request.getURI().getPath().contains("/login/in")){
            //放行
            return  chain.filter(exchange);
        }
        //3 获取token
        String token = request.getHeaders().getFirst("token");

        //4 是否有token
        if (StringUtils.isBlank(token)){
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();
        }
        //5 token是否有效
        try {
            //5.1 有效 重置header 路由到微服务
            Claims claimsBody = AppJwtUtil.getClaimsBody(token);
            //验证是否有效
            int result = AppJwtUtil.verifyToken(claimsBody);
            if (result==1||result==2){
                //5.2 无效 返回401
                response.setStatusCode(HttpStatus.UNAUTHORIZED);
                return response.setComplete();
            }
            //合法 向header中重新设置userId
            Integer userId = (Integer) claimsBody.get("id");

            //重新设置token到header中
            ServerHttpRequest serverHttpRequest = request.mutate().headers(new Consumer<HttpHeaders>() {
                @Override
                public void accept(HttpHeaders httpHeaders) {
                    httpHeaders.add("userId", userId + "");
                }
            }).build();
            exchange.mutate().request(serverHttpRequest).build();
        }catch (Exception e){
            e.printStackTrace();
            //5.2 无效 返回401
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();
        }
        return chain.filter(exchange);
    }
         /**
        *@Description:优先级设置 值越小 优先级越高
        *@Parameter:
        *@Return:
        **/
    @Override
    public int getOrder() {
        return 0;
    }
}
